package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.mapping.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        nodeParse(rootElement,namespace,"//select",SqlCommandType.SELECT);//查询
        nodeParse(rootElement,namespace,"//insert",SqlCommandType.INSERT);//插入
        nodeParse(rootElement,namespace,"//update",SqlCommandType.UPDATE);//更新
        nodeParse(rootElement,namespace,"//delete",SqlCommandType.DELETE);//删除
    }

    private void nodeParse(Element rootElement, String namespace, String nodesName, SqlCommandType sqlCommandType){

        List<Element> list = rootElement.selectNodes(nodesName);
        if (list != null && !list.isEmpty()){
            for (Element element : list) {
                String id = element.attributeValue("id");
                configuration.getMappedStatementMap().put(namespace+"."+id,getMappedStatement(element,sqlCommandType));
            }
        }
    }

    private MappedStatement getMappedStatement(Element element, SqlCommandType sqlCommandType){
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String parameterType = element.attributeValue("parameterType");
        String sqlText = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParameterType(parameterType);
        mappedStatement.setSql(sqlText);
        mappedStatement.setSqlCommandType(sqlCommandType);
        return mappedStatement;
    }
}
